/****************************************************************************
 *
 *   Copyright (C) 2019 PX4 Development Team. All rights reserved.
 *   Adapted for STM32H743 FreeRTOS by Zarek Chen, 2024
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file blocking_queue.hpp
 * @brief Thread-safe blocking queue implementation using FreeRTOS
 *
 * This is a C++ template class that provides a fixed-size blocking queue
 * using FreeRTOS semaphores for synchronization. It's based on PX4's
 * BlockingQueue implementation but adapted for FreeRTOS.
 */

#pragma once

#include "../px4_sem.h"
#include <stddef.h>

/**
 * @class BlockingQueue
 * @brief Thread-safe blocking queue with fixed capacity
 *
 * This queue uses two semaphores to implement blocking behavior:
 * - sem_head: Counts available slots (initialized to N)
 * - sem_tail: Counts available items (initialized to 0)
 *
 * When the queue is full, push() blocks until space is available.
 * When the queue is empty, pop() blocks until an item is available.
 *
 * @tparam T The type of items stored in the queue
 * @tparam N The maximum capacity of the queue
 *
 * Usage:
 * @code
 * BlockingQueue<int, 10> queue;
 * 
 * // Producer thread
 * queue.push(42);
 * 
 * // Consumer thread
 * int value = queue.pop();
 * @endcode
 */
template<class T, size_t N>
class BlockingQueue
{
public:
	/**
	 * @brief Constructor - initializes the queue
	 */
	BlockingQueue()
	{
		px4_sem_init(&_sem_head, 0, N);      // N slots available
		px4_sem_init(&_sem_tail, 0, 0);      // 0 items available
		px4_sem_setprotocol(&_sem_head, SEM_PRIO_NONE);
		px4_sem_setprotocol(&_sem_tail, SEM_PRIO_NONE);
	}

	/**
	 * @brief Destructor - cleans up semaphores
	 */
	~BlockingQueue()
	{
		px4_sem_destroy(&_sem_head);
		px4_sem_destroy(&_sem_tail);
	}

	// Delete copy constructor and assignment operator
	BlockingQueue(const BlockingQueue &) = delete;
	BlockingQueue &operator=(const BlockingQueue &) = delete;

	/**
	 * @brief Push an item to the queue (blocking)
	 * 
	 * If the queue is full, this function blocks until space is available.
	 * 
	 * @param newItem The item to push
	 */
	void push(T newItem)
	{
		// Wait for available slot
		do {} while (px4_sem_wait(&_sem_head) != 0);

		// Add item to queue
		_data[_tail] = newItem;
		_tail = (_tail + 1) % N;

		// Signal that an item is available
		px4_sem_post(&_sem_tail);
	}

	/**
	 * @brief Pop an item from the queue (blocking)
	 * 
	 * If the queue is empty, this function blocks until an item is available.
	 * 
	 * @return The popped item
	 */
	T pop()
	{
		// Wait for available item
		do {} while (px4_sem_wait(&_sem_tail) != 0);

		// Get item from queue
		T ret = _data[_head];
		_head = (_head + 1) % N;

		// Signal that a slot is available
		px4_sem_post(&_sem_head);

		return ret;
	}

private:
	px4_sem_t _sem_head;  ///< Semaphore for available slots
	px4_sem_t _sem_tail;  ///< Semaphore for available items

	T _data[N] {};        ///< Circular buffer for data

	size_t _head{0};      ///< Head index (read position)
	size_t _tail{0};      ///< Tail index (write position)
};

